<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/1
 * Time: 16:09
 */
namespace app\common\helper;

class appmenu_helper
{
    /**
     * 通过接口取得新的access_token
     * @param int $appid
     * @param int $serect
     * @return boolean
     */
    public static function get_access_token_new($appid, $serect)
    {
        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$serect;
        $response = curl($token_url);
        if (isset($response->access_token)) {
            return $response->access_token;
        }

        return false;
    }

    /**
     * 通过接口取得新的access_token
     * @param unknown_type $token_url
     * @return boolean
     */
    public static function get_access_token($token_url)
    {
        $response = curl($token_url);
        if (isset($response->access_token)) {
            return $response->access_token;
        }

        return false;
    }

    /**
     * 取自定义菜单
     * @param int $parent_id
     * @param int $open_card_id
     * @param int $company_id
     * @return array
     */
    public static function get_menu_list_for_weixin($parent_id = 0, $store_id = 0)
    {
        $filter = array('store_id'=>$store_id, 'parent_id'=>$parent_id, 'status'=>1);

        $list = getList('appmenu', $filter, ['view_order', 'asc'], 0);
        foreach ($list as $k=>$v) {
            $filter['parent_id'] = $v['id'];
            $list[$k]['son_list'] = getList('appmenu', $filter, ['view_order', 'DESC'], 0);
        }

        return $list;
    }


    /**
     * 拼装自定义菜单click事件的key
     * @param int $id
     * @param int $type
     * @param string $details
     * @return String
     * @example key值为：V{$menu_id}_C_{$type}_{$appmsg_id}
     */
    public static function menu_details_key($id, $type, $details)
    {
        // 链接
        if ($type == 10 || $type == 60) {
            return $details;
        } else if (in_array($type, array(1, 20, 50))) {
            return 'V'.$id.'_C_'.$type.'_'.$id;
        }

        // 图文
        return 'V'.$id.'_C_'.$type.'_'.$details;
    }

    /**
     * 添加/更新wx_menuid
     * @param int $store_id
     * @param int $wx_menuid
     * @return int
     */
    public static function add_appmenu_store($store_id, $wx_menuid)
    {
        $old_info = self::get_appmenu_store_info($store_id);
        if (!$old_info) {
            $new_info = array(
                'store_id'  => $store_id,
                'wx_menuid' => $wx_menuid
            );
            $id = _model('appmenu_store')->create($new_info);
        } else {
            $id = $old_info['id'];

            _model('appmenu_store')->update($id, array('wx_menuid'=>$wx_menuid));
        }

        return $id;
    }

    /**
     * 获取appmenu_info
     * @param int $store_id
     */
    public static function get_appmenu_store_info($store_id)
    {
        return _uri('appmenu_store', array('store_id'=>$store_id));
    }

}